package com.powerhua.cms.web.servlet;

import com.powerhua.core.bean.BeansRegisterLocator;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.powerhua.cms.web.servlet.action.ActionInterface;

public class CmsServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8727356251756840373L;

	/**
	 * 
	 */ 
	public void init() throws ServletException {
		super.init();
	}

	/**
	 * 
	 */
	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		doPost(req, res);
	}

	/**
	 * 
	 */
	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		res.setCharacterEncoding("UTF-8");
		String svlet = req.getParameter("servlet");

		// action
		ActionInterface action = (ActionInterface)BeansRegisterLocator.getBean(svlet);
		
		// action result
		String result = action.doAction(req);
		
		// dispatcher
		Object objForward = req.getAttribute("forward");
		if(objForward != null && (Boolean)objForward) {
			RequestDispatcher requestDispacher = req.getRequestDispatcher(result);
			requestDispacher.forward(req, res);
			return;
		} 
		
		// redirect
		Object objRedirect = req.getAttribute("redirect");
		if(objRedirect != null) {
			return;
		}
		
		// write directly
		PrintWriter out = res.getWriter();
		out.print(result);
		return;
	}

	/**
	 * 
	 */
	public String getServletInfo() {
		return "Action servlet information.";
	}

}
